package com.xin.data.simbapesa.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.view.LayoutInflater;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.IntentSenderRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.google.gson.JsonObject;
import com.xin.data.simbapesa.PathMaping;
import com.xin.data.simbapesa.SimbaApp;
import com.xin.data.simbapesa.adapter.FragmentPagerAdapter;
import com.xin.data.simbapesa.api.PU;
import com.xin.data.simbapesa.api.RxHttp;
import com.xin.data.simbapesa.api.U;
import com.xin.data.simbapesa.base.BaseActivity;
import com.xin.data.simbapesa.base.BaseDialog;
import com.xin.data.simbapesa.base.BaseParams;
import com.xin.data.simbapesa.databinding.SimbaHomeActivityBinding;
import com.xin.data.simbapesa.device.ImmediateUpdateManager;
import com.xin.data.simbapesa.dialog.LimitDialog;
import com.xin.data.simbapesa.dialog.UpdateDialog;
import com.xin.data.simbapesa.fragment.ChatFragment;
import com.xin.data.simbapesa.fragment.RePayFragment;
import com.xin.data.simbapesa.fragment.SettingFragment;
import com.xin.data.simbapesa.fragment.StateFragment1;
import com.xin.data.simbapesa.fragment.StateFragment2;
import com.xin.data.simbapesa.obj.SimbaAmountIsUpInfo;
import com.xin.data.simbapesa.utils.AESCryptUtilJar;
import com.xin.data.simbapesa.utils.DateUtils;
import com.xin.data.simbapesa.utils.JsonParse;
import com.xin.data.simbapesa.utils.LogUtil;
import com.xin.data.simbapesa.utils.NumUtils;
import com.xin.data.simbapesa.utils.OrderUtils;
import com.xin.data.simbapesa.utils.PhoneUtils;
import com.xin.data.simbapesa.utils.SpUtils;
import com.xin.data.simbapesa.utils.ViewUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;

public class SimbaHomeActivity extends BaseActivity<SimbaHomeActivityBinding> implements StateFragment1.OnRefreshState1Listener, StateFragment2.OnRefreshState2Listener {


    StateFragment1 fragment1;
    StateFragment2 fragment2;

    RePayFragment rePayFragment;

    SettingFragment settingFragment;

    ChatFragment chatFragment;

    FragmentPagerAdapter adapter;
    List<Fragment> fragments;


    LimitDialog limitDialog;

    int state;

    boolean isCheck;

    ImmediateUpdateManager updateManager = null;

    UpdateDialog updateDialog;


    @Override
    protected SimbaHomeActivityBinding initViewBinding(LayoutInflater inflater) {
        return SimbaHomeActivityBinding.inflate(inflater);
    }

    @Override
    protected void initView() {

        binding.getRoot().setPadding(0, 0, 0, 0);

        fragments = new ArrayList<>();


        state = OrderUtils.getOrderStatus();

        LogUtil.e("me", "state 1->" + state);

        if (state <= 0) {
            fragment1 = new StateFragment1();
            fragments.add(fragment1);
        } else if (state <= 3) {
            fragment2 = new StateFragment2();
            fragments.add(fragment2);
        } else {
            rePayFragment = new RePayFragment();
            fragments.add(rePayFragment);
        }

        chatFragment=new ChatFragment();
        settingFragment=new SettingFragment();
        fragments.add(chatFragment);
        fragments.add(settingFragment);

        adapter = new FragmentPagerAdapter(getSupportFragmentManager(), getLifecycle(), fragments);
        binding.viewPager.setOffscreenPageLimit(3);
        binding.viewPager.setAdapter(adapter);
        binding.viewPager.registerOnPageChangeCallback(myCallback);


        binding.tab1.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P181, "");
            toggleTab(0);
            toggleFragment(0);
        });
        binding.tab2.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P183, "");
            toggleTab(2);
            toggleFragment(2);
        });

        binding.tab3.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P182, "");
            toggleTab(1);
            toggleFragment(1);
        });

        binding.getRoot().post(new Runnable() {
            @Override
            public void run() {
                if ((PhoneUtils.isUpdate(getActivity()) || PhoneUtils.isForceUpdate(getActivity()))) {
                    boolean isUpdate = SpUtils.get_boolean(getActivity(), SpUtils.KEY_UPDATE + "_" + U.URL_PHONE + "_" + DateUtils.getYear() + "_" + DateUtils.getMonth() + "_" + DateUtils.getDay());
                    if (!isUpdate) {
                        initUpdate();
                        showUpdateDialog();
                        SpUtils.save_boolean(SimbaApp.getInstance(), SpUtils.KEY_UPDATE + "_" + U.URL_PHONE + "_" + DateUtils.getYear() + "_" + DateUtils.getMonth() + "_" + DateUtils.getDay(), true);
                    }
                }
            }
        });

    }

    @Override
    protected void initData() {
        UP_TYPE1 = PU.P11;
        UP_TYPE2 = PU.P12;

        toggleTab(0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }

    ViewPager2.OnPageChangeCallback myCallback = new ViewPager2.OnPageChangeCallback() {
        @SuppressLint("RtlHardcoded")
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            toggleTab(position);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            super.onPageScrolled(position, positionOffset, positionOffsetPixels);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            super.onPageScrollStateChanged(state);
        }
    };

    void loadData() {
        amountIsUp();
        PU.queryDeviceInfoTypes(this);
        userProcess(new UserProcessInterface() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onRequestResult() {
                int state1 = OrderUtils.getOrderStatus();

                LogUtil.e("me", state + "<-state 2->" + state1 + ",isCheck->" + isCheck);

                if (!isCheck) {
                    isCheck = true;
                    checkCode();
                }

                if (state1 != state) {
                    state = state1;
                    fragments.clear();
                    if (state <= 0) {
                        //申请
                        fragment1 = new StateFragment1();
                        fragments.add(fragment1);
                    } else if (state <= 3) {
                        //审核
                        fragment2 = new StateFragment2();
                        fragments.add(fragment2);
                    } else {
                        //还款
                        rePayFragment = new RePayFragment();
                        fragments.add(rePayFragment);
                    }

                    chatFragment=new ChatFragment();
                    settingFragment=new SettingFragment();
                    fragments.add(chatFragment);
                    fragments.add(settingFragment);

                    LogUtil.e("me", "fragments->" + fragments.size());
                    adapter = new FragmentPagerAdapter(getSupportFragmentManager(), getLifecycle(), fragments);
                    binding.viewPager.setOffscreenPageLimit(3);
                    binding.viewPager.setAdapter(adapter);
                    binding.viewPager.registerOnPageChangeCallback(myCallback);

                }
            }
        }, false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    void toggleTab(int position) {
        switch (position) {
            case 0:
                binding.tab1Title.setSelected(true);
                binding.tab2Title.setSelected(false);
                binding.tab3Title.setSelected(false);
                break;
            case 1:
                binding.tab1Title.setSelected(false);
                binding.tab2Title.setSelected(false);
                binding.tab3Title.setSelected(true);
                break;
            case 2:
                binding.tab1Title.setSelected(false);
                binding.tab2Title.setSelected(true);
                binding.tab3Title.setSelected(false);
                break;
        }
    }

    void toggleFragment(int position) {
        binding.viewPager.setCurrentItem(position);
    }

    void showLimitDialog(String amout1, String amout2) {
        if (getActivity() != null && !isFinishing() && binding != null) {
            if (limitDialog == null) {
                limitDialog = new LimitDialog(getActivity());
            }
            limitDialog.setData(U.URL_PRODUCT_NAME, NumUtils.formatToTwoDecimals(Double.parseDouble(amout1)), NumUtils.formatToTwoDecimals(Double.parseDouble(amout2)));
            limitDialog.setOnBtnClickListener(new BaseDialog.BtnClickListener() {
                @Override
                public void btnOnClickOk() {
                    toApply();
                    PU.userBuriedPoint(PU.P209, amout1 + "$$" + amout2);
                }

                @Override
                public void btnOnClickCancel() {

                }

                @Override
                public void btnOnClickColse() {

                }
            });
            limitDialog.show();
            PU.userBuriedPoint(PU.P208, "");
        }
        LogUtil.e("me", "--showLimitDialog--");
    }

    void toApply() {

        boolean isAllPermissionsGranted = true;
        if (SimbaApp.getInstance().getAppInfo().getPermission() != null) {
            for (String permission : SimbaApp.getInstance().getAppInfo().getPermission()) {
                if (permission.equals("android.permission.READ_SMS") && ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
                    isAllPermissionsGranted = false;
                    break;
                }
            }
        }

        LogUtil.e("me", "isAllPermissionsGranted->" + isAllPermissionsGranted);

        if (isAllPermissionsGranted) {
            PU.sendDevice();
            String token = SpUtils.get_string(getActivity(), SpUtils.KEY_TOKEN, "");
            userProcess(token, () -> {
                boolean isCheckSteps = checkSteps();
                if (!isCheckSteps) {
                    startActivity(new Intent(getActivity(), SimbaApplyActivity.class));
                }
            }, true);
        } else {
            startActivity(new Intent(getActivity(), SimbaPermissionDesActivity.class));
        }
    }


    void amountIsUp() {
        String token = SpUtils.get_string(getActivity(), SpUtils.KEY_TOKEN, "");
        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[83], U.URL_MAIN_PRODUCT, token);
//        json.addProperty("selectAmount", "80000000");
        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_MAIN_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }
        String data = AESCryptUtilJar.encryptDefault(json.toString());
        LogUtil.e("me", json + "<-amountIsUp post->" + data);
        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        if (!TextUtils.isEmpty(s)) {
                            String json1 = AESCryptUtilJar.decryptDefault(s);
                            LogUtil.e("me", "amountIsUp json->" + json1);
                            if (JsonParse.getCode(json1)) {
                                SimbaAmountIsUpInfo bean = JsonParse.amountIsUpJson2Obj(json1);
                                if (bean != null && bean.getOpenFlag().equals("YES") && !TextUtils.isEmpty(bean.getAmount()) && !TextUtils.isEmpty(bean.getOldAmount())) {
                                    double f1 = Double.parseDouble(NumUtils.filterDigits(bean.getAmount()));
                                    double f2 = Double.parseDouble(NumUtils.filterDigits(bean.getOldAmount()));
                                    if (f1 > f2) {
                                        showLimitDialog(bean.getOldAmount(), bean.getAmount());
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        if (e != null) {
                            LogUtil.e("me", "amountIsUp e->" + e);
                        }
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    final ActivityResultLauncher<IntentSenderRequest> updateLauncher =
            registerForActivityResult(new ActivityResultContracts.StartIntentSenderForResult(),
                    result -> {
                        try {
                            if (result.getResultCode() == RESULT_OK) {
                                SpUtils.save_boolean(SimbaApp.getInstance(), SpUtils.KEY_UPDATE + "_" + U.URL_PHONE + "_" + DateUtils.getYear() + "_" + DateUtils.getMonth() + "_" + DateUtils.getDay(), true);
                            }
                        } catch (Exception e) {
                            LogUtil.e("me", "updateLauncher e->" + e);
                        }
                    });

    void initUpdate() {
        try {
            updateManager = new ImmediateUpdateManager(this, true, updateLauncher, null);
        } catch (Exception e) {
        }
    }

    void showUpdateDialog() {
        if (!isFinishing() && binding != null && SimbaApp.getInstance().getAppInfo() != null && SimbaApp.getInstance().getAppInfo().getUpdateInfo() != null) {
            updateDialog = new UpdateDialog(getActivity());
            updateDialog.setOnBtnClickListener(new UpdateDialog.BtnClickListener() {
                @Override
                public void btnOnClickOk() {
                    PU.userBuriedPoint(PU.P301, "");
                    if (updateManager != null) {
                        updateManager.checkAndStartUpdateAsync(new Function0<Unit>() {
                            @Override
                            public Unit invoke() {
                                return null;
                            }
                        }, null);
                    }
                }

                @Override
                public void btnOnClickCancel() {
                    PU.userBuriedPoint(PU.P302, "");
                }

                @Override
                public void btnOnClickColse() {
                    PU.userBuriedPoint(PU.P302, "");
                }
            });
            updateDialog.setData(SimbaApp.getInstance().getAppInfo().getUpdateInfo());
            updateDialog.show();
            PU.userBuriedPoint(PU.P300, "");
        }
    }



    @Override
    public void onLoadData() {
        loadData();
    }


    @Override
    public void onLoadState() {
        loadData();
    }

    @Override
    public void onSwitchFragment(int position) {
        toggleTab(position);
        toggleFragment(position);
    }



}
